package com.inlycat.web.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.inlycat.entity.UserInfo;
import com.inlycat.service.UserInfoService;

/**
 * @author jarvan4dev@163.com
 * @since 2015年8月24日下午4:24:41
 * @category 
 **/

@Controller
@RequestMapping("/userInfo")
public class UserInfoController {
	
	private static final Logger logger = LoggerFactory
			.getLogger(UserInfoController.class);
	
	@Resource
	private UserInfoService userInfoService;

	@RequestMapping(value="/update",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update(@Valid UserInfo userInfo,BindingResult bResult){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (bResult.hasErrors()) {
			resultMap.put("code", 0);
			List<String> messages = new LinkedList<String>();
			for (FieldError error : bResult.getFieldErrors()) {
				messages.add(error.getDefaultMessage());
			}
			resultMap.put("message", messages);
			logger.info("message", messages);
			return resultMap;
		}
		boolean result = userInfoService.updateSelective(userInfo);
		if(result){
			resultMap.put("code", 1);
			resultMap.put("message", "success");
		}else{
			resultMap.put("code", 0);
			resultMap.put("message", "fail");
		}
		return resultMap;
	}
	
	@RequestMapping(value="/select",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> select(Long userId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		UserInfo userInfo = userInfoService.selectByUserId(userId);
		if(userInfo==null){
			resultMap.put("code", 0);
			resultMap.put("message", "未查询出用户信息");
		}else{
			resultMap.put("code", 1);
			resultMap.put("message", "success");
			resultMap.put("data", userInfo);
		}
		return resultMap;
	}

}
